package com.dream.service.recommender.splitter.zk;

import com.dream.service.recommender.domain.splitter.PlacementConfig;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;

/**
 * Created by zhiji on 2016/4/26.
 */
public class ZkOperator {

    private String connectstring;
    private int timeout = 1000;
    private ZkClient zkClient;

    public ZkOperator() {}

    public ZkOperator(String connectstring) {
        this(connectstring, 1000);
    }

    public ZkOperator(String connectstring, int timeout) {
        setConnectstring(connectstring);
        setTimeout(timeout);
    }

    public String getConnectstring() {
        return connectstring;
    }

    public void setConnectstring(String connectstring) {
        this.connectstring = connectstring;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public ZkClient getZkClient() {
        return zkClient;
    }

    public void setZkClient(ZkClient zkClient) {
        this.zkClient = zkClient;
    }

    public void init(String connectstring, int timeout) {
        zkClient = new ZkClient(connectstring, timeout);
        zkClient.setZkSerializer(new SerializableSerializer());
    }

    public PlacementConfig getData(String path) {
        return zkClient.readData(path);
    }

    public void setData(String path, PlacementConfig data) {
        zkClient.writeData(path, data);
    }

    public String createPath(String path, Object data) {
        return zkClient.create(path, data, CreateMode.EPHEMERAL);
    }

    public void close() {
        zkClient.close();
    }
}
